package app.util
{
	import flash.filesystem.*;
	
	public class Config
	{	
		public var allowRestrict:Boolean;
		public var alwaysFront:Boolean;
		public var allowPreview:Boolean;
		public var enableLog:Boolean;

		public function loadDefault():void
		{
			this.allowRestrict = false;
			this.alwaysFront = false;
			this.allowPreview = true;
			this.enableLog = true;
			
			Mediator.getLogger().log("Load default config");
		}
		
		public function buildFromFile():void
		{			
			try
			{				
				var configXml:XML;
				var configFile:File = new File
					(File.applicationDirectory.resolvePath(Constants.CONFIG_FILE).nativePath);
				var fs:FileStream = new FileStream(); 					
				fs.open(configFile, FileMode.READ); 
				configXml = XML(fs.readUTFBytes(fs.bytesAvailable)); 
				fs.close();

				this.allowRestrict = this.getBooleanValue(configXml, "allowRestrict");
				this.allowPreview = this.getBooleanValue(configXml, "allowPreview");
				this.alwaysFront = this.getBooleanValue(configXml, "alwaysFront");
				this.enableLog = this.getBooleanValue(configXml, "enableLog");
				
			}
			catch(e:Error)
			{
				Mediator.getLogger().log("Load config file error : " + e.message);
				this.loadDefault();
			}
		}
		
		public function writeToFile():void
		{
			var fs:FileStream = new FileStream(); 
			var xmlString:String = "";
			fs.open(new File(
				File.applicationDirectory.resolvePath(Constants.CONFIG_FILE).nativePath), FileMode.WRITE);

			xmlString += this.generateHeader();
			xmlString += this.generateLeftNode("config");
			xmlString += this.generateNode("allowRestrict", this.allowRestrict.toString());		
			xmlString += this.generateNode("allowPreview", this.allowPreview.toString());	
			xmlString += this.generateNode("alwaysFront", this.alwaysFront.toString());	
			xmlString += this.generateNode("enableLog", this.enableLog.toString());	
			xmlString += this.generateRightNode("config");
			
			fs.writeUTFBytes(xmlString); 
			fs.close(); 
			
			Mediator.alert("Save current settings to file done");
		}
		
		private function getBooleanValue(xml:XML, prop:String):Boolean
		{
			var str:String = String(xml[prop]).toLowerCase();
			if(str == "true") return true;
			if(str == "false") return false;
			throw new Error("Invalid boolean value <" + str + "> for " + prop);
		}
		
		private function generateHeader():String {
			return '<?xml version="1.0" encoding="utf-8"?>\n';
		}

		private function generateNode(nodeName:String, nodeValue:String):String {
			var node:String = "<" + nodeName + ">" + nodeValue + "</" + nodeName + ">\n";
			return node;
		}
		
		private function generateLeftNode(nodeName:String):String {
			return "<" + nodeName + ">\n";
		}
		
		private function generateRightNode(nodeName:String):String {
			return "</" + nodeName + ">\n";
		}		
	}
}